﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Threading;
using ZedGraph;
using Microsoft.Office.Interop.Excel;
//using Dev.PubLib;

namespace Xfoil_call
{
    public partial class main_form : Form
    {
        ///////////////////////////////////////////////////////////
        string Ppath = null;                       //declare working path string.
        string foilpath = null;                    //declare airfoil file path string.
        string cppath = null;                      //declare Cp data file path string.
        string parapath = null;                    //declare parameters file path string.
        bool delxfoil = false;                     //declare delete xfoil.exe flag.
        ///////////////////////////////////////////////////////////
        
        public main_form()
        {
            InitializeComponent();
        }
       
        /////////////////////////////////////////////////////////
        //quit the software event.///////////////////////////////
        private void quit_menu_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
            try
            {
                if (delxfoil == true)                              //delete the xfoil.exe in working directory when exit.
                {
                    string xfoilpath = Ppath + "\\xfoil.exe";
                    File.Delete(xfoilpath);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请确认文件是否已经被删除或者被重命名。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /////////////////////////////////////////////////////////
        //display the help document./////////////////////////////
        //error code 001.////////////////////////////////////////
        private void guide_menu_Click(object sender, EventArgs e)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = "help.pdf";
                p.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请确认帮助文档是否\r\n存在或者被重命名。\r\nEC:001", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////////
        //display the software declaration.//////////////////////
        //error code 002.////////////////////////////////////////
        private void about_menu_Click(object sender, EventArgs e)
        {
            try
            {
                about_form aboutform = new about_form();
                aboutform.Show();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:002", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////////
        //calculate operation.///////////////////////////////////
        private void cal_button_Click(object sender, EventArgs e)
        {
            string[] foil = foil_text.Text.Trim().Split('\\');                          //airfoil directory level judgement.
            if (foil.Length >= 8)
            {
                MessageBox.Show("请将翼型文件放置的目录层级减小到8以下，以便xfoil调用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string[] mastring = ma_text.Text.Trim().Split(' ');                         //ma_text judgement.
            double judgema;
            foreach (string sma in mastring)
            {
                if (!double.TryParse(sma.Trim(), out judgema))
                {
                    MessageBox.Show("请确保马赫数输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            string[] xtrstring = xtr_text.Text.Trim().Split(' ');                        //xtr_text judgement.
            double judgextr;
            foreach (string sxtr in xtrstring)
            {
                if (!double.TryParse(sxtr.Trim(), out judgextr))
                {
                    MessageBox.Show("请确保转捩点输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (xtr_text.Text.Trim().IndexOf(' ') == -1)                              //if there is not a space value in it.
            {
                MessageBox.Show("请修改转捩点位置至合适的值，或者保持原本参数。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string[] alfa0string = aoa0_text.Text.Trim().Split(' ');                  //aoa0_text judgement.
            double judgealfa0;
            foreach (string salfa in alfa0string)
            {
                if (!double.TryParse(salfa.Trim(), out judgealfa0))
                {
                    MessageBox.Show("请确保起始迎角输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            string[] restring = re_text.Text.Trim().Split(' ');                      //re_text judgement.
            double judgere;
            foreach (string sre in restring)
            {
                if (!double.TryParse(sre.Trim(), out judgere))
                {
                    MessageBox.Show("请确保雷诺数输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            string alfa1string = aoa1_text.Text.Trim();                             //aoa1_text judgement.
            double judgealfa1;
            if (!double.TryParse(alfa1string, out judgealfa1))
            {
                MessageBox.Show("请确保终止迎角输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string yjjgstring = yjjg_text.Text.Trim();                             //yjjg_text judgement.
            double judgeyjjg;
            if (!double.TryParse(yjjgstring, out judgeyjjg))
            {
                MessageBox.Show("请确保迎角间隔输入栏没有不合理字符。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //airfoil file judgement.
            if (foil_text.Text.Substring(1, 2) == ":\\")
            {
                FileStream exfoil = new FileStream(foil_text.Text, FileMode.Open, FileAccess.Read);
                StreamReader exfoilreader = new StreamReader(exfoil);
                exfoilreader.ReadLine();
                string exfoilline = exfoilreader.ReadLine();
                double exex = 0.0;
                string[] exfoildata = exfoilline.Trim().Split(new char[] { ' ', '\t' });
                foreach (string exdata in exfoildata)
                {
                    if (!string.IsNullOrEmpty(exdata))
                    {
                        if (double.TryParse(exdata, out exex))
                        {
                        }
                        else
                        {
                            MessageBox.Show("请选择合适的翼型文件。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            exfoilreader.Close();
                            exfoil.Close();
                            return;
                        }
                    }
                }
                exfoilreader.Close();
                exfoil.Close();
            }

            Directory.SetCurrentDirectory(Ppath);
            string currentpath = Directory.GetCurrentDirectory() + "\\";
            DirectoryInfo rootdir = new DirectoryInfo(currentpath + "outcome");
            if (!rootdir.Exists)
            {
                rootdir.Create();                                                 //create the outcome dir.
            }
            DirectoryInfo dir0 = new DirectoryInfo(rootdir + "\\" + DateTime.Now.ToString("yyyy-MM-dd HH-m-ss"));
            if (!dir0.Exists)
            {
                dir0.Create();                                                   //create the outcome data dir for a calculation.
            }
            string[] dirany = dir0.FullName.Split('\\');
            if (dirany.Length > 7)                                                 //output data dir level judgement.
            {
                MessageBox.Show("请勿使工作目录层级大于7！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            List<string> malist = new List<string>();                            //get Mach number list.
            foreach (string tempmastring in mastring)
            {
                if (!string.IsNullOrEmpty(tempmastring.Trim()))
                {
                    malist.Add(tempmastring);
                }
            }

            for (int ima = 0; ima < malist.Count; ima++)
            {
                //bool vissys;
                if (nonviscous_singlebutton.Checked == true && viscous_singlebutton.Checked == false)//nonviscous status.
                {
                    //vissys = false;
                    //PubSyswareCom.SetParameter("", "viscous", vissys);
                    double yjjg = double.Parse(yjjg_text.Text.Trim());
                    if (aoa1_text.Enabled == false && yjjg_text.Enabled == false)                    //discontinuous points.
                    {
                        string[] aoa0temp = aoa0_text.Text.Trim().Split(' ');
                        foreach (string aoatemp in aoa0temp)
                        {
                            if (!string.IsNullOrEmpty(aoatemp))
                            {
                                cal_nonviscous_spoint(dir0, malist[ima], aoatemp, null, null);
                            }
                        }
                    }
                    else                                                                             //continuous points.
                    {
                        double aoa0 = double.Parse(aoa0_text.Text.Trim());
                        double aoa1 = double.Parse(aoa1_text.Text.Trim());
                        if ((aoa1 > aoa0 && yjjg > 0) || (aoa1 < aoa0 && yjjg < 0))
                        {
                            cal_nonviscous_mpoints(dir0, malist[ima], aoa0_text.Text.Trim(), aoa1_text.Text.Trim(), yjjg_text.Text.Trim(), null, null);
                        }
                        else
                        {
                            MessageBox.Show("请输入合理的起始、结束迎角及迎角间隔！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                    }
                }
                else if (nonviscous_singlebutton.Checked == false && viscous_singlebutton.Checked == true)//viscous status.
                {
                    //vissys = true;
                    //PubSyswareCom.SetParameter("", "viscous", vissys);
                    double yjjg = double.Parse(yjjg_text.Text.Trim());
                    if (aoa1_text.Enabled == false && yjjg_text.Enabled == false)                         //discontinuous points.
                    {
                        string[] aoa0temp = aoa0_text.Text.Trim().Split(' ');
                        foreach (string aoatemp in aoa0temp)
                        {
                            if (!string.IsNullOrEmpty(aoatemp))
                            {
                                cal_viscous_spoint(dir0, malist[ima], aoatemp, null, null);
                            }
                        }
                    }
                    else                                                                                 //continuous points.
                    {
                        double aoa0 = double.Parse(aoa0_text.Text.Trim());
                        double aoa1 = double.Parse(aoa1_text.Text.Trim());
                        if ((aoa1 > aoa0 && yjjg > 0) || (aoa1 < aoa0 && yjjg < 0))
                        {
                            cal_viscous_mpoints(dir0, malist[ima], aoa0_text.Text.Trim(), aoa1_text.Text.Trim(), yjjg_text.Text.Trim(), null, null);
                        }
                        else
                        {
                            MessageBox.Show("请输入合理的起始、结束迎角及迎角间隔！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请选择“无粘”或者“有粘”！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            //interface to sysware.
            //Process[] threads = Process.GetProcesses();
            //foreach (Process th in threads)
            //{
            //    if (th.ProcessName.ToUpper().Equals("SYSWAREIDE"))
            //    {
            //        //send Mach numbers to sysware.
            //        double[] masys = new double[mastring.Length];
            //        int jmasys = 0;
            //        for (int imasys = 0; imasys < mastring.Length; imasys++)
            //        {
            //            if (!string.IsNullOrEmpty(mastring[imasys]))
            //            {
            //                masys[jmasys] = double.Parse(mastring[imasys]);
            //                jmasys++;
            //            }
            //        }
            //        PubSyswareCom.mSetArrayParameter("", "Mach_numbers", masys);
            //        //send xtr setting to sysware.
            //        PubSyswareCom.SetParameter("", "transition_points", xtr_text.Text.Trim());
            //        //send aoa0 setting to sysware.
            //        double[] aoa0sys = new double[alfa0string.Length];
            //        int jaoa0sys = 0;
            //        for (int iaoa0sys = 0; iaoa0sys < alfa0string.Length; iaoa0sys++)
            //        {
            //            if (!string.IsNullOrEmpty(alfa0string[iaoa0sys]))
            //            {
            //                aoa0sys[jaoa0sys] = double.Parse(alfa0string[iaoa0sys]);
            //                jaoa0sys++;
            //            }
            //        }
            //        PubSyswareCom.mSetArrayParameter("", "Starting_AOA_or_AOAs", aoa0sys);
            //        //send Reynold's number to sysware.
            //        PubSyswareCom.SetParameter("", "Reynolds_number", re_text.Text.Trim());
            //        //send aoa1 setting to sysware.
            //        PubSyswareCom.SetParameter("", "Ending_AOA", aoa1_text.Text.Trim());
            //        //send yjjg setting to sysware.
            //        PubSyswareCom.SetParameter("", "AOA_interval", yjjg_text.Text.Trim());

            //        //send data back.
            //        string currpath = Convert.ToString(dir0) + "\\";
            //        DirectoryInfo syspath = new DirectoryInfo(currpath);
            //        FileInfo[] sysfiles = syspath.GetFiles();
            //        List<List<double>> syspara = new List<List<double>>();
            //        foreach (FileInfo sysfile in sysfiles)
            //        {
            //            if (sysfile.Name == "outdata.cfg")
            //            {
            //                FileStream sysparafile = new FileStream(sysfile.FullName, FileMode.Open, FileAccess.Read);
            //                StreamReader sysparareader = new StreamReader(sysparafile);
            //                string r = sysparareader.ReadLine();
            //                while (!string.IsNullOrEmpty(r))
            //                {
            //                    string[] ds = r.Trim().Split(' ');
            //                    List<double> syspararow = new List<double>();
            //                    foreach (string s in ds)
            //                    {
            //                        if (!string.IsNullOrEmpty(s))
            //                        {
            //                            syspararow.Add(double.Parse(s));
            //                        }
            //                    }
            //                    syspara.Add(syspararow);
            //                }
            //                sysparareader.Close();
            //                sysparafile.Close();
            //            }
            //        }
            //        List<double> clsys = new List<double>();
            //        List<double> cdsys = new List<double>();
            //        List<double> cmsys = new List<double>();
            //        List<double> ldsys = new List<double>();
            //        for (int sysi = 0; sysi < syspara.Count; sysi++)
            //        {
            //            clsys.Add(syspara[sysi][2]);
            //            cdsys.Add(syspara[sysi][3]);
            //            cmsys.Add(syspara[sysi][5]);
            //            if (syspara[sysi][2] == 10086.0)
            //            {
            //                ldsys.Add(10086.0);
            //            }
            //            else
            //            {
            //                ldsys.Add(syspara[sysi][2] / syspara[sysi][3]);
            //            }
            //        }
            //        PubSyswareCom.mSetArrayParameter("", "cl", clsys.ToArray());
            //        PubSyswareCom.mSetArrayParameter("", "cd", cdsys.ToArray());
            //        PubSyswareCom.mSetArrayParameter("", "cm", cmsys.ToArray());
            //        PubSyswareCom.mSetArrayParameter("", "K", ldsys.ToArray());
            //    }
            //}
        }


        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //calculate non-viscous single point status.///////////////////////////////////////////////////////////
        //error code 003.//////////////////////////////////////////////////////////////////////////////////////
        private void cal_nonviscous_spoint(DirectoryInfo dir, string ma, string aoa, object sender, EventArgs e)
        {
            try
            {
                string foil = foil_text.Text.Trim();                                        //get airfoil information.
                bool flag;                                                           //foreign airfoil judgment flag.
                string foilf;                                                        //declare airfoil name string.
                Directory.SetCurrentDirectory(Ppath);
                string relativepath = dir.FullName.Substring(dir.FullName.LastIndexOf("\\") + 1, dir.FullName.Length - dir.FullName.LastIndexOf("\\") - 1);

                //handle the string of foil to differ internal or external airfoil.////////////////////////////
                if (foil.Substring(1, 2) == ":\\")                                   //external airfoil.
                {
                    int i1 = foil.LastIndexOf("\\");
                    int i2 = foil.LastIndexOf(".");
                    foilf = foil.Substring(i1 + 1, i2 - i1 - 1);
                    flag = true;
                }
                else                                                                 //internal airfoil.
                {
                    foilf = foil;
                    flag = false;
                }

                //generate call.bat.///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                FileStream callfile = new FileStream(Ppath + "\\call.bat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter callw = new StreamWriter(callfile);
                callw.Write("xfoil.exe <command.dat");
                callw.Close();
                callfile.Close();

                //generate command.dat.//////////////////////////////////////////////////////////////////////////////////
                FileStream c = new FileStream(Ppath + "\\command.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter w = new StreamWriter(c);
                if (flag == true)
                {                                                                   //load external airfoil.
                    FileStream d = new FileStream(dir + "\\" + foilf + ".dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    File.Copy(foil, dir.FullName + "\\" + foilf + ".dat", true);    //copy external airfoil into destination.
                    d.Close();
                    w.WriteLine("load outcome\\" + relativepath + "\\" + foilf + ".dat");
                }
                else
                {
                    w.WriteLine(foil);
                    if (!File.Exists(dir.FullName + "\\" + foilf + ".dat"))
                    {
                        w.WriteLine("save outcome\\" + relativepath + "\\" + foilf + ".dat");    //load and save internal airfoil.
                    }
                }
                w.WriteLine("pane");
                w.WriteLine("norm");
                w.WriteLine("oper");
                w.WriteLine("mach " + ma);
                w.WriteLine("alfa " + aoa);
                w.WriteLine("cpwr");
                w.WriteLine("outcome\\" + relativepath + "\\cp_A" + aoa + "_Ma" + ma + ".dat");
                w.WriteLine("pacc");
                w.WriteLine("outcome\\" + relativepath + "\\P_As" + aoa + "_Ma" + ma + ".dat");
                w.WriteLine("");
                w.WriteLine("alfa " + aoa);
                w.WriteLine("pacc");
                w.WriteLine("");
                w.WriteLine("quit");
                w.Close();
                c.Close();

                FileStream cfg = new FileStream(dir.FullName + "\\deployment.cfg", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(cfg);                              //write the configure file.
                writer.WriteLine("Nonviscous");
                writer.Close();
                cfg.Close();

                //call xfoil.////////////////////////////////////////////
                Process p = new Process();
                p.StartInfo.FileName = "call.bat";
                p.Start();
                p.WaitForExit(12000);                                                      //wait for finish the calculation,and, if not, may be some mistakes upon subsequent process.

                //delete the order files./////////////////////////////////////////
                cppath = dir.FullName + "\\cp_A" + aoa + "_Ma" + ma + ".dat";
                parapath = dir.FullName + "\\P_As" + aoa + "_Ma" + ma + ".dat";            //assign parameters data path.
                string commandfile = Ppath + "\\command.dat";
                string delcallfile = Ppath + "\\call.bat";
                foilpath = Convert.ToString(dir.FullName + "\\" + foilf + ".dat");         //assign airfoil file path.
                File.Delete(commandfile);                                                  //delete command.dat.
                File.Delete(delcallfile);                                                  //delete call.bat.

                file_tree.Nodes.Clear();                                                   //refresh and reload file tree.
                load_tree(null, null);

                //dealing empty or NaN data.
                string[] browstringall = File.ReadAllLines(parapath);
                if (browstringall[12].IndexOf("NaN") >= 0)
                {
                    string[] bnans = browstringall[12].Trim().Split(' ');
                    List<string> bnanstring = new List<string>();
                    foreach (string bnan in bnans)
                    {
                        if (!string.IsNullOrEmpty(bnan))
                        {
                            bnanstring.Add(bnan);
                        }
                    }
                    browstringall[12] = "  " + bnanstring[0] + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                }
                if (string.IsNullOrEmpty(browstringall[12]))
                {
                    browstringall[12] = "  " + aoa + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                }
                FileStream b = new FileStream(parapath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                StreamWriter bwriter = new StreamWriter(b);
                for (int i6 = 0; i6 < browstringall.Length; i6++)
                {
                    bwriter.WriteLine(browstringall[i6]);
                }
                bwriter.Close();
                show_data(b);                                                              //call to show data in data_text.
                b.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:003", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //calculate non-viscous multi points status./////////////////////////////////////////////////////////////////////////////////////
        //error code 004.////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void cal_nonviscous_mpoints(DirectoryInfo dir, string ma, string aoa0, string aoa1, string yjjg, object sender, EventArgs e)
        {
            try
            {
                //get texts info.////////////////////////////////////
                string foil = foil_text.Text.Trim();                                          //get airfoil information.
                double a0 = double.Parse(aoa0);
                double a1 = double.Parse(aoa1);
                double jg = double.Parse(yjjg);
                if (((a1 - a0) % jg) != 0)                                                    //re-set ending angle for xfoil.
                {
                    a1 = Math.Round(a0 + jg * ((int)((a1 - a0) / jg)), 3);
                }

                bool flag;                                                                    //foreign airfoil judgment flag.
                string foilf;                                                                 //declare airfoil name string.
                Directory.SetCurrentDirectory(Ppath);
                string relativepath = dir.FullName.Substring(dir.FullName.LastIndexOf("\\") + 1, dir.FullName.Length - dir.FullName.LastIndexOf("\\") - 1);

                //handle the string of foil0.////////////////////////////////////////////
                if (foil.Substring(1, 2) == ":\\")
                {                                                                             //external airfoil.
                    int i1 = foil.LastIndexOf("\\");
                    int i2 = foil.LastIndexOf(".");
                    foilf = foil.Substring(i1 + 1, i2 - i1 - 1);
                    flag = true;
                }
                else
                {
                    foilf = foil;                                                             //internal airfoil.
                    flag = false;
                }

                //generate call.bat.///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                FileStream callfile = new FileStream(Ppath + "\\call.bat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter callw = new StreamWriter(callfile);
                callw.Write("xfoil.exe <command.dat");
                callw.Close();
                callfile.Close();

                //generate command.dat.//////////////////////////////////////////////////////////////////////////////////
                FileStream c = new FileStream(Ppath + "\\command.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter w = new StreamWriter(c);
                if (flag == true)
                {                                                                            //load external airfoil.
                    FileStream d = new FileStream(dir + "\\" + foilf + ".dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    File.Copy(foil, dir.FullName + "\\" + foilf + ".dat", true);             //copy external airfoil into destination.
                    d.Close();
                    w.WriteLine("load outcome\\" + relativepath + "\\" + foilf + ".dat");
                }
                else
                {
                    w.WriteLine(foil);
                    if (!File.Exists(dir.FullName + "\\" + foilf + ".dat"))
                    {
                        w.WriteLine("save outcome\\" + relativepath + "\\" + foilf + ".dat");          //load and save internal airfoil.
                    }
                }
                w.WriteLine("pane");
                w.WriteLine("norm");
                w.WriteLine("oper");
                w.WriteLine("mach " + ma);
                if (a0 < a1)
                {
                    for (double i = a0; i <= a1; i = i + jg)                                     //calculate every aoa increase status.
                    {
                        i = Math.Round(i, 3);                                                //if not,may be some wrong appear when i approach to zero.
                        string atemp = Convert.ToString(i);
                        w.WriteLine("alfa " + atemp);
                        w.WriteLine("cpwr");
                        w.WriteLine("outcome\\" + relativepath + "\\cp_A" + atemp + "_Ma" + ma + ".dat");
                        cppath = dir.FullName + "\\cp_A" + atemp + "_Ma" + ma + ".dat";
                    }
                }
                else
                {
                    for (double i = a0; i >= a1; i = i + jg)                                 //calculate every aoa decrease status.
                    {
                        i = Math.Round(i, 3);
                        string atemp = Convert.ToString(i);
                        w.WriteLine("alfa " + atemp);
                        w.WriteLine("cpwr");
                        w.WriteLine("outcome\\" + relativepath + "\\cp_A" + atemp + "_Ma" + ma + ".dat");
                        cppath = dir.FullName + "\\cp_A" + atemp + "_Ma" + ma + ".dat";
                    }
                }
                w.WriteLine("pacc");
                w.WriteLine("outcome\\" + relativepath + "\\P_A" + aoa0 + "_" + aoa1 + "_Ma" + ma + ".dat");
                parapath = dir.FullName + "\\P_A" + aoa0 + "_" + aoa1 + "_Ma" + ma + ".dat";
                w.WriteLine("");
                w.WriteLine("aseq " + aoa0 + " " + aoa1 + " " + yjjg);
                w.WriteLine("pacc");
                w.WriteLine("");
                w.WriteLine("quit");
                w.Close();
                c.Close();

                FileStream cfg = new FileStream(dir.FullName + "\\deployment.cfg", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(cfg);                             //write the configure file.
                writer.WriteLine("Nonviscous");
                writer.Close();
                cfg.Close();

                //call xfoil.////////////////////////////////////////////
                Process p = new Process();
                p.StartInfo.FileName = "call.bat";
                p.Start();
                p.WaitForExit(12000);

                //delete the order files./////////////////////////
                string commandfile = Ppath + "\\command.dat";
                string delcallfile = Ppath + "\\call.bat";
                foilpath = Convert.ToString(dir.FullName + "\\" + foilf + ".dat");
                File.Delete(commandfile);                                                //delete command.dat.
                File.Delete(delcallfile);                                                //delete call.bat.

                file_tree.Nodes.Clear();                                                 //refresh and reload file tree.
                load_tree(null, null);

                //dealing empty or NaN data.
                int bparacount = (int)((a1 - a0) / jg + 1);
                string[] browstringall = File.ReadAllLines(parapath);
                for (int i = 12; i < browstringall.Length; i++)
                {
                    if (browstringall[i].IndexOf("NaN") >= 0)
                    {
                        string[] bnans = browstringall[i].Trim().Split(' ');
                        List<string> bnanstring = new List<string>();
                        foreach (string bnan in bnans)
                        {
                            if (!string.IsNullOrEmpty(bnan))
                            {
                                bnanstring.Add(bnan);
                            }
                        }
                        browstringall[i] = "  " + bnanstring[0] + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                    }
                }
                string[] bpararowall = new string[bparacount + 12];
                for (int i0 = 0; i0 < 12; i0++)                                              //read in 12 lines.
                {
                    bpararowall[i0] = browstringall[i0];
                }
                List<List<double>> bparalist = new List<List<double>>();
                for (int i1 = 12; i1 < browstringall.Length; i1++)                           //read in double list
                {
                    string[] bpararow = browstringall[i1].Trim().Split(' ');
                    List<double> brow = new List<double>();
                    foreach (string bpara in bpararow)
                    {
                        if (!string.IsNullOrEmpty(bpara))
                        {
                            brow.Add(double.Parse(bpara));
                        }
                    }
                    bparalist.Add(brow);
                }
                int i3 = 0, i4 = 12, i5 = 12;
                for (int i2 = 0; i2 < bparacount; i2++)
                {
                    double alfa = Math.Round(a0 + i2 * jg, 3);
                    if (bparalist[i3][0] == alfa)
                    {
                        bpararowall[i4] = browstringall[i5];
                        i3++;
                        i4++;
                        i5++;
                    }
                    else
                    {
                        bpararowall[i4] = "  " + alfa.ToString("f3") + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                        i4++;
                    }
                }

                FileStream b = new FileStream(parapath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                StreamWriter bwriter = new StreamWriter(b);
                for (int i6 = 0; i6 < bpararowall.Length; i6++)
                {
                    bwriter.WriteLine(bpararowall[i6]);
                }
                bwriter.Close();
                show_data(b);                                                           //call to show data in data_text.
                b.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:004", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////
        //calculate viscous single point status.///////////////////////////////////////////////////////////
        //error code 005.//////////////////////////////////////////////////////////////////////////////////
        private void cal_viscous_spoint(DirectoryInfo dir, string ma, string aoa, object sender, EventArgs e)
        {
            try
            {
                //get texts info.////////////////////////////////////
                string foil = foil_text.Text.Trim();
                string xtr = xtr_text.Text.Trim();                                                    //get transition point information.
                string re = re_text.Text.Trim();                                                      //get Reynold number information.

                bool flag;
                string foilf;
                Directory.SetCurrentDirectory(Ppath);
                string relativepath = dir.FullName.Substring(dir.FullName.LastIndexOf("\\") + 1, dir.FullName.Length - dir.FullName.LastIndexOf("\\") - 1);

                //handle the string of foil0.////////////////////////////////////////////
                if (foil.Substring(1, 2) == ":\\")
                {                                                                              //external airfoil.
                    int i1 = foil.LastIndexOf("\\");
                    int i2 = foil.LastIndexOf(".");
                    foilf = foil.Substring(i1 + 1, i2 - i1 - 1);
                    flag = true;
                }
                else
                {                                                                              //internal airfoil.
                    foilf = foil;
                    flag = false;
                }

                //generate call.bat./////////////////////////////////////////////////////////////////////////////////////////
                FileStream callfile = new FileStream(Ppath + "\\call.bat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter callw = new StreamWriter(callfile);
                callw.Write("xfoil.exe <command.dat");
                callw.Close();
                callfile.Close();

                //generate command.dat.//////////////////////////////////////////////////////////////////////////////////
                FileStream c = new FileStream(Ppath + "\\command.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter w = new StreamWriter(c);
                if (flag == true)
                {                                                                            //load external airfoil.
                    FileStream d = new FileStream(dir + "\\" + foilf + ".dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    File.Copy(foil, dir.FullName + "\\" + foilf + ".dat", true);             //copy external airfoil into destination.
                    d.Close();
                    w.WriteLine("load outcome\\" + relativepath + "\\" + foilf + ".dat");
                }
                else
                {
                    w.WriteLine(foil);
                    if (!File.Exists(dir.FullName + "\\" + foilf + ".dat"))
                    {
                        w.WriteLine("save outcome\\" + relativepath + "\\" + foilf + ".dat");          //load and save internal airfoil.
                    }
                }
                w.WriteLine("pane");
                w.WriteLine("norm");
                w.WriteLine("oper");
                w.WriteLine("visc " + re);
                w.WriteLine("mach " + ma);
                w.WriteLine("vpar");
                w.WriteLine("xtr " + xtr);
                w.WriteLine();
                w.WriteLine("alfa " + aoa);
                w.WriteLine("cpwr");
                w.WriteLine("outcome\\" + relativepath + "\\cp_A" + aoa + "_Ma" + ma + ".dat");
                cppath = dir.FullName + "\\cp_A" + aoa + "_Ma" + ma + ".dat";
                w.WriteLine("pacc");
                w.WriteLine("outcome\\" + relativepath + "\\P_As" + aoa + "_Ma" + ma + ".dat");
                parapath = dir.FullName + "\\P_As" + aoa + "_Ma" + ma + ".dat";
                w.WriteLine("");
                w.WriteLine("alfa " + aoa);
                w.WriteLine("pacc");
                w.WriteLine("");
                w.WriteLine("quit");
                w.Close();
                c.Close();

                FileStream cfg = new FileStream(dir.FullName + "\\deployment.cfg", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(cfg);                               //write th configure file.
                writer.WriteLine("Re " + re);
                writer.WriteLine("xtr " + xtr);
                writer.Close();
                cfg.Close();

                //call xfoil.////////////////////////////////////////////
                Process p = new Process();
                p.StartInfo.FileName = "call.bat";
                p.Start();
                p.WaitForExit(12000);

                //delete the order files./////////////////////////
                string commandfile = Ppath + "\\command.dat";
                string delcallfile = Ppath + "\\call.bat";
                foilpath = Convert.ToString(dir.FullName + "\\" + foilf + ".dat");
                File.Delete(commandfile);                                                  //delete command.dat.
                File.Delete(delcallfile);                                                  //delete call.bat.

                file_tree.Nodes.Clear();                                                   //refresh and reload file tree.
                load_tree(null, null);

                //dealing empty or NaN data.
                string[] browstringall = File.ReadAllLines(parapath);
                if (browstringall[12].IndexOf("NaN") >= 0)
                {
                    string[] bnans = browstringall[12].Trim().Split(' ');
                    List<string> bnanstring = new List<string>();
                    foreach (string bnan in bnans)
                    {
                        if (!string.IsNullOrEmpty(bnan))
                        {
                            bnanstring.Add(bnan);
                        }
                    }
                    browstringall[12] = "  " + bnanstring[0] + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                }
                if (string.IsNullOrEmpty(browstringall[12]))
                {
                    browstringall[12] = "  " + aoa + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                }
                FileStream b = new FileStream(parapath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                StreamWriter bwriter = new StreamWriter(b);
                for (int i6 = 0; i6 < browstringall.Length; i6++)
                {
                    bwriter.WriteLine(browstringall[i6]);
                }
                bwriter.Close();
                show_data(b);                                                              //call to show data in data_text.
                b.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:005", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //calculation subroutine./////////////////////////////////////////////////////////////////////////////////////////////////////
        //error code 006./////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private void cal_viscous_mpoints(DirectoryInfo dir, string ma, string aoa0, string aoa1, string yjjg, object sender, EventArgs e)
        {
            try
            {
                //get texts info.////////////////////////////////////
                string foil = foil_text.Text.Trim();
                string xtr = xtr_text.Text.Trim();
                string re = re_text.Text.Trim();
                double a0 = double.Parse(aoa0);
                double a1 = double.Parse(aoa1);
                double jg = double.Parse(yjjg);
                if (((a1 - a0) % jg) != 0)                                                    //re-set ending angle for xfoil.
                {
                    a1 = Math.Round(a0 + jg * ((int)((a1 - a0) / jg)), 3);
                }

                bool flag;
                string foilf;
                Directory.SetCurrentDirectory(Ppath);
                string relativepath = dir.FullName.Substring(dir.FullName.LastIndexOf("\\") + 1, dir.FullName.Length - dir.FullName.LastIndexOf("\\") - 1);

                //handle the string of foil0.////////////////////////
                if (foil.Substring(1, 2) == ":\\")
                {                                                                            //get airfoil name and flag.
                    int i1 = foil.LastIndexOf("\\");
                    int i2 = foil.LastIndexOf(".");
                    foilf = foil.Substring(i1 + 1, i2 - i1 - 1);
                    flag = true;
                }
                else
                {
                    foilf = foil;
                    flag = false;
                }

                //generate call.bat.///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                FileStream callfile = new FileStream(Ppath + "\\call.bat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter callw = new StreamWriter(callfile);
                callw.Write("xfoil.exe <command.dat");
                callw.Close();
                callfile.Close();

                //generate command.dat.///////////////////////////////////////
                FileStream c = new FileStream(Ppath + "\\command.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter w = new StreamWriter(c);
                if (flag == true)
                {                                                                            //load external airfoil.
                    FileStream d = new FileStream(dir + "\\" + foilf + ".dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    File.Copy(foil, dir.FullName + "\\" + foilf + ".dat", true);             //copy external airfoil into destination.
                    d.Close();
                    w.WriteLine("load outcome\\" + relativepath + "\\" + foilf + ".dat");
                }
                else
                {
                    w.WriteLine(foil);
                    if (!File.Exists(dir.FullName + "\\" + foilf + ".dat"))
                    {
                        w.WriteLine("save outcome\\" + relativepath + "\\" + foilf + ".dat");            //load and save internal airfoil.
                    }
                }
                w.WriteLine("pane");
                w.WriteLine("norm");
                w.WriteLine("oper");
                w.WriteLine("visc " + re);
                w.WriteLine("mach " + ma);
                w.WriteLine("vpar");
                w.WriteLine("xtr " + xtr);
                w.WriteLine();
                if (a0 < a1)
                {
                    for (double i = a0; i <= a1; i = i + jg)                                   //calculate every aoa status for increase aoas.
                    {
                        i = Math.Round(i, 3);
                        string atemp = Convert.ToString(i);
                        w.WriteLine("alfa " + atemp);
                        w.WriteLine("cpwr");
                        w.WriteLine("outcome\\" + relativepath + "\\cp_A" + atemp + "_Ma" + ma + ".dat");
                        cppath = dir.FullName + "\\cp_A" + atemp + "_Ma" + ma + ".dat";
                    }
                }
                else
                {
                    for (double i = a0; i >= a1; i = i + jg)                                  //calculate every aoa status for decrease aoas.
                    {
                        i = Math.Round(i, 3);
                        string atemp = Convert.ToString(i);
                        w.WriteLine("alfa " + atemp);
                        w.WriteLine("cpwr");
                        w.WriteLine("outcome\\" + relativepath + "\\cp_A" + atemp + "_Ma" + ma + ".dat");
                        cppath = dir.FullName + "\\cp_A" + atemp + "_Ma" + ma + ".dat";
                    }
                }
                w.WriteLine("pacc");
                w.WriteLine("outcome\\" + relativepath + "\\P_A" + aoa0 + "_" + aoa1 + "_Ma" + ma + ".dat");
                parapath = dir.FullName + "\\P_A" + aoa0 + "_" + aoa1 + "_Ma" + ma + ".dat";
                w.WriteLine("");
                w.WriteLine("aseq " + aoa0 + " " + aoa1 + " " + yjjg);
                w.WriteLine("pacc");
                w.WriteLine("");
                w.WriteLine("quit");
                w.Close();
                c.Close();

                FileStream cfg = new FileStream(dir.FullName + "\\deployment.cfg", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(cfg);                                 //write the configure file.
                writer.WriteLine("Re " + re);
                writer.WriteLine("xtr " + xtr);
                writer.Close();
                cfg.Close();

                //call xfoil.////////////////////////////////////////////
                Process p = new Process();
                p.StartInfo.FileName = "call.bat";
                p.Start();
                p.WaitForExit(12000);

                //delete the order files./////////////////////////
                string commandfile = Ppath + "\\command.dat";
                string delcallfile = Ppath + "\\call.bat";
                foilpath = Convert.ToString(dir.FullName + "\\" + foilf + ".dat");
                File.Delete(commandfile);                                                //delete command.dat.
                File.Delete(delcallfile);                                                //delete call.bat.

                file_tree.Nodes.Clear();                                                 //refresh and reload file tree.
                load_tree(null, null);

                //dealing empty or NaN data.
                int bparacount = (int)((a1 - a0) / jg + 1);
                string[] browstringall = File.ReadAllLines(parapath);
                for (int i = 12; i < browstringall.Length; i++)
                {
                    if (browstringall[i].IndexOf("NaN") >= 0)
                    {
                        string[] bnans = browstringall[i].Trim().Split(' ');
                        List<string> bnanstring = new List<string>();
                        foreach (string bnan in bnans)
                        {
                            if (!string.IsNullOrEmpty(bnan))
                            {
                                bnanstring.Add(bnan);
                            }
                        }
                        browstringall[i] = "  " + bnanstring[0] + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                    }
                }
                string[] bpararowall = new string[bparacount + 12];
                for (int i0 = 0; i0 < 12; i0++)                                              //read in 12 lines.
                {
                    bpararowall[i0] = browstringall[i0];
                }
                List<List<double>> bparalist = new List<List<double>>();
                for (int i1 = 12; i1 < browstringall.Length; i1++)                           //read in double list
                {
                    string[] bpararow = browstringall[i1].Trim().Split(' ');
                    List<double> brow = new List<double>();
                    foreach (string bpara in bpararow)
                    {
                        if (!string.IsNullOrEmpty(bpara))
                        {
                            brow.Add(double.Parse(bpara));
                        }
                    }
                    bparalist.Add(brow);
                }
                int i3 = 0, i4 = 12, i5 = 12;
                for (int i2 = 0; i2 < bparacount; i2++)
                {
                    double alfa = Math.Round(a0 + i2 * jg, 3);
                    if (bparalist[i3][0] == alfa)
                    {
                        bpararowall[i4] = browstringall[i5];
                        i3++;
                        i4++;
                        i5++;
                    }
                    else
                    {
                        bpararowall[i4] = "  " + alfa.ToString("f3") + "  10086.0  10086.0  10086.0  10086.0  10086.0  10086.0";
                        i4++;
                    }
                }

                FileStream b = new FileStream(parapath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
                StreamWriter bwriter = new StreamWriter(b);
                for (int i6 = 0; i6 < bpararowall.Length; i6++)
                {
                    bwriter.WriteLine(bpararowall[i6]);
                }
                bwriter.Close();
                show_data(b);                                                           //call to show data in data_text.
                b.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:006", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ////////////////////////////////////////////////////////
        //load welcome screen and select working directory./////
        //error code 007.///////////////////////////////////////
        private void main_form_Load(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog open = new FolderBrowserDialog();                        //open save-to-dir dialog.
                open.Description = "选择目录层级小于5级的工作目录：";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    Ppath = open.SelectedPath;                                               //set Ppath string as a user defined dir value.
                    FileStream xfoilfile = new FileStream(Ppath + "\\xfoil.exe", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    string xfoilsfile = System.IO.Directory.GetCurrentDirectory() + "\\xfoil.exe";
                    string xfoildfile = Ppath + "\\xfoil.exe";                               
                    if (!File.Exists(xfoilsfile))
                    {
                        throw new FileNotFoundException();
                    }
                    File.Copy(xfoilsfile, xfoildfile, true);                                 //copy xfoil.exe into destination dir.
                    xfoilfile.Close();
                    delxfoil = true;
                } 
                else
                {
                    Ppath = System.IO.Directory.GetCurrentDirectory();
                    delxfoil = false;
                }

                welcome_form welcomeform = new welcome_form();                              //load welcome form.
                welcomeform.Show();

                //interface to sysware.
                //Process[] threads = Process.GetProcesses();
                //foreach (Process th in threads)
                //{
                //    if (th.ProcessName.ToUpper().Equals("SYSWAREIDE"))
                //    {
                //        //get data setting from sysware.
                //        object vis = null;
                //        object xtr = null;
                //        object re = null;
                //        object ma = null;
                //        object aoa0 = null;
                //        object aoa1 = null;
                //        object yjjg = null;
                //        PubSyswareCom.GetParameter("", "viscous", ref vis);
                //        PubSyswareCom.GetParameter("", "transition_points", ref xtr);
                //        PubSyswareCom.GetParameter("", "Reynolds_number", ref re);
                //        PubSyswareCom.mGetArrayParameter("", "Mach_numbers", ref ma);
                //        PubSyswareCom.mGetArrayParameter("", "Starting_AOA_or_AOAs", ref aoa0);
                //        PubSyswareCom.GetParameter("", "Ending_AOA", ref aoa1);
                //        PubSyswareCom.GetParameter("", "AOA_interval", ref yjjg);
                //        if ((!xtr.Equals(0)) && (!vis.Equals(0)) && (!re.Equals(0)) && (!aoa1.Equals(0)) && (!yjjg.Equals(0)) && (ma != null) && (aoa0 != null))
                //        {
                //            //viscous setting.
                //            bool vistemp = Convert.ToBoolean(vis);
                //            if (vistemp == true)
                //            {
                //                xtr_text.Enabled = false;
                //                viscous_singlebutton.Checked = false;
                //                re_text.Enabled = false;
                //            }
                //            else
                //            {
                //                xtr_text.Enabled = true;
                //                nonviscous_singlebutton.Checked = false;
                //                re_text.Enabled = true;
                //            }

                //            //transition points setting.
                //            xtr_text.Text = Convert.ToString(xtr);

                //            //Retnold's number setting.
                //            if (re != null)
                //            {
                //                re_text.Text = Convert.ToString(re);
                //            }

                //            //Mach numbers setting.
                //            if (ma is object[])
                //            {
                //                object[] temm = ma as object[];
                //                for (int i = 0; i < temm.Count(); i++)
                //                {
                //                    ma_text.Text = ma_text.Text + Convert.ToString(temm[i]) + " ";
                //                }
                //            }

                //            //AOA0 setting.
                //            if (aoa0 is object[])
                //            {
                //                object[] tema0 = ma as object[];
                //                for (int i = 0; i < tema0.Count(); i++)
                //                {
                //                    aoa0_text.Text = aoa0_text.Text + Convert.ToString(tema0[i]) + " ";
                //                }
                //            }

                //            //AOA1 setting.
                //            if (aoa1 != null)
                //            {
                //                aoa1_text.Text = Convert.ToString(aoa1);
                //            }

                //            //AOA interval setting.
                //            if (yjjg != null)
                //            {
                //                yjjg_text.Text = Convert.ToString(yjjg);
                //            }
                //        }
                //        else
                //        {
                //            nonviscous_singlebutton.Checked = false;
                //            viscous_singlebutton.Checked = false;
                //            foil_text.Text = "naca 0008";
                //            xtr_text.Text = "1 1";
                //            re_text.Text = "3e6";
                //            ma_text.Text = "0";
                //            aoa0_text.Text = "0";
                //            aoa1_text.Text = "0";
                //            yjjg_text.Text = "0";
                //        }
                //    }
                //}
                nonviscous_singlebutton.Checked = false;
                viscous_singlebutton.Checked = false;
                foil_text.Text = "naca 2412";
                xtr_text.Text = "0.5 0.5";
                re_text.Text = "3e6";
                ma_text.Text = "0.3";
                aoa0_text.Text = "-2";
                aoa1_text.Text = "3";
                yjjg_text.Text = "0.2";
                //load file tree.
                load_tree(null, null);                           
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:007", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////
        //read in data and show in data_text.//////////////
        //error code 008.//////////////////////////////////
        private void show_data(FileStream b)
        {
            try
            {
                //b's name string is a parameter's data file route string.
                int bbackslash = b.Name.LastIndexOf("\\");
                int bdot = b.Name.LastIndexOf(".");
                string bpname = b.Name.Substring(bbackslash + 1, bdot - bbackslash - 1);                 //get the b's name.
                List<List<double>> paralist = new List<List<double>>();                                  //parameters list.
                List<string> parastring = new List<string>();                                            //parameters all row-string list.
                if (bpname.IndexOf("P_As") >= 0)                                                         //for single point parameters.
                {
                    DirectoryInfo datedir = new DirectoryInfo(b.Name.Substring(0, bbackslash + 1));
                    FileInfo[] allpfiles = datedir.GetFiles();
                    foreach (FileInfo pfile in allpfiles)                                                //traversing every file in the dir.
                    { 
                        int pbackslash = pfile.FullName.LastIndexOf("\\");
                        int pdot = pfile.FullName.LastIndexOf(".");
                        string pname = pfile.FullName.Substring(pbackslash + 1, pdot - pbackslash);
                        if (pname.IndexOf("P_A") >= 0)                                                   //if it is a parameters data file.
                        {
                            int malocation = pname.LastIndexOf("_Ma");                                   //get Mach number.
                            int dot = pname.LastIndexOf(".");
                            double ma = double.Parse(pname.Substring(malocation + 3, dot - malocation - 3));
                            List<double> pararow = new List<double>();
                            string paradatastr = null;
                            FileStream parafile = new FileStream(pfile.FullName, FileMode.Open, FileAccess.Read);
                            StreamReader reader = new StreamReader(parafile);
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            string emptyYN = reader.ReadLine();
                            if (!string.IsNullOrEmpty(emptyYN.Trim()))
                            {
                                paradatastr = Convert.ToString(ma) + emptyYN;
                                parastring.Add(paradatastr);
                                string[] paraArr = paradatastr.Trim().Split(' ');
                                foreach (string s in paraArr)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                paralist.Add(pararow);
                            }
                            reader.Close();
                            parafile.Close();
                        }
                    }
                    //ordering the paralist from minimum to maximum.
                    for (int imaorder = 0; imaorder < paralist.Count - 1; imaorder++)               //ordered by mach number.
                    {
                        for (int jmaorder = imaorder + 1; jmaorder < paralist.Count; jmaorder++)
                        {
                            if (paralist[imaorder][0] > paralist[jmaorder][0])
                            {
                                string temp = null;
                                List<double> templist = new List<double>();
                                templist = paralist[imaorder];
                                paralist[imaorder] = paralist[jmaorder];
                                paralist[jmaorder] = templist;
                                temp = parastring[imaorder];
                                parastring[imaorder] = parastring[jmaorder];
                                parastring[jmaorder] = temp;
                            }
                        }
                    }
                    for (int ialfaorder = 0; ialfaorder < paralist.Count - 1; ialfaorder++)        //ordered by alfa.
                    {
                        for (int jalfaorder = ialfaorder + 1; jalfaorder < paralist.Count; jalfaorder++)
                        {
                            if ((paralist[ialfaorder][0] == paralist[jalfaorder][0]) && (paralist[ialfaorder][1] > paralist[jalfaorder][1]))
                            {
                                string temp = null;
                                List<double> templist = new List<double>();
                                templist = paralist[ialfaorder];
                                paralist[ialfaorder] = paralist[jalfaorder];
                                paralist[jalfaorder] = templist;
                                temp = parastring[ialfaorder];
                                parastring[ialfaorder] = parastring[jalfaorder];
                                parastring[jalfaorder] = temp;
                            }
                        }
                    }
                }
                else                                                                             //for multi points.
                {
                    DirectoryInfo datedir = new DirectoryInfo(b.Name.Substring(0, bbackslash + 1));
                    FileInfo[] allpfiles = datedir.GetFiles();
                    foreach (FileInfo pfile in allpfiles)                                        //traversing every file in the dir.
                    {
                        int pbackslash = pfile.FullName.LastIndexOf("\\");
                        int pdot = pfile.FullName.LastIndexOf(".");
                        string pname = pfile.FullName.Substring(pbackslash + 1, pdot - pbackslash);
                        if (pname.IndexOf("P_A") >= 0)                                           //if it is a parameters data file.
                        {
                            int malocation = pname.LastIndexOf("_Ma");                           //get the Mach number.
                            int dot = pname.LastIndexOf(".");
                            double ma = double.Parse(pname.Substring(malocation + 3, dot - malocation - 3));
                            string paradatastr = null;
                            FileStream parafile = new FileStream(pfile.FullName, FileMode.Open, FileAccess.Read);
                            StreamReader reader = new StreamReader(parafile);
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            reader.ReadLine();
                            while (!string.IsNullOrEmpty(paradatastr = reader.ReadLine()))
                            {
                                paradatastr = Convert.ToString(ma) + paradatastr;
                                parastring.Add(paradatastr);
                                string[] paraArr = paradatastr.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in paraArr)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                paralist.Add(pararow);
                            }
                            reader.Close();
                            parafile.Close();
                        }
                    }
                    //ordering the paralist from minimum to maximum.
                    for (int imaorder = 0; imaorder < paralist.Count - 1; imaorder++)               //ordered by mach number.
                    {
                        for (int jmaorder = imaorder + 1; jmaorder < paralist.Count; jmaorder++)
                        {
                            if (paralist[imaorder][0] > paralist[jmaorder][0])
                            {
                                string temp = null;
                                List<double> templist = new List<double>();
                                templist = paralist[imaorder];
                                paralist[imaorder] = paralist[jmaorder];
                                paralist[jmaorder] = templist;
                                temp = parastring[imaorder];
                                parastring[imaorder] = parastring[jmaorder];
                                parastring[jmaorder] = temp;
                            }
                        }
                    }
                    for (int ialfaorder = 0; ialfaorder < paralist.Count - 1; ialfaorder++)        //ordered by alfa.
                    {
                        for (int jalfaorder = ialfaorder + 1; jalfaorder < paralist.Count; jalfaorder++)
                        {
                            if ((paralist[ialfaorder][0] == paralist[jalfaorder][0]) && (paralist[ialfaorder][1] > paralist[jalfaorder][1]))
                            {
                                string temp = null;
                                List<double> templist = new List<double>();
                                templist = paralist[ialfaorder];
                                paralist[ialfaorder] = paralist[jalfaorder];
                                paralist[jalfaorder] = templist;
                                temp = parastring[ialfaorder];
                                parastring[ialfaorder] = parastring[jalfaorder];
                                parastring[jalfaorder] = temp;
                            }
                        }
                    }
                }

                data_text.Text = "";                                                                //clear the data_text content.
                data_text.Text = "Ma    alpha    CL        CD       CDp       CM     Top_Xtr  Bot_Xtr\r\n---- ------ -------- --------- --------- -------- -------- --------\r\n";
                FileStream para = new FileStream(b.Name.Substring(0, bbackslash + 1) + "outdata.cfg", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(para);                                       //create and save ordered data into file.
                for (int ipara = 0; ipara < parastring.Count; ipara++)
                {
                    data_text.Text = data_text.Text + parastring[ipara] + "\r\n";
                    writer.WriteLine(parastring[ipara]);
                }
                writer.Close();
                para.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:008", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////
        //load history operation directories and files.//
        //error code 009./////////////////////////////////
        private void load_tree(object sender,EventArgs e)
        {
            try
            {
                string path0 = Ppath + "\\outcome\\";                                    //get the working path string.
                DirectoryInfo outcome = new DirectoryInfo(path0);
                if (!outcome.Exists)
                {
                    outcome.Create();                                                    //if not, root node creation error.
                }
                string[] dirday = Directory.GetDirectories(path0);
                int jday=0, jfile=0;                                                     //define internal loop variable.

                file_tree.ShowLines = true;
                TreeNode noderoot = file_tree.Nodes.Add("A", "工作目录", 1, 2);          //root node.

                for (int iday = 0; iday < dirday.Length; iday++)
                {
                    //day directories node./////////////////////////////////
                    jday = dirday[iday].LastIndexOf("\\");
                    string dayname = dirday[iday].Substring(jday + 1, dirday[iday].Length - jday - 1);
                    TreeNode nodeday = new TreeNode(dayname, 2, 3);
                    noderoot.Nodes.Add(nodeday);

                    //data files node.///////////////////////////
                    string[] files = Directory.GetFiles(dirday[iday]);
                    for (int ifile = 0; ifile < files.Length; ifile++)
                    {
                        jfile = files[ifile].LastIndexOf("\\");
                        string filename = files[ifile].Substring(jfile + 1, files[ifile].Length - jfile - 1);
                        if (filename.IndexOf("cp_A") >= 0)
                        {
                            TreeNode nodefile = new TreeNode(filename, 3, 4);
                            nodeday.Nodes.Add(nodefile);
                        }  
                    }
                    nodeday.Collapse();                                                    //data file node collapsed.
                }
                noderoot.Expand();                                                         //day tree struct expand only.
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:009", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //////////////////////////////////////////////////////////////////////////
        //load foreign airfoil directory./////////////////////////////////////////
        //error code 010./////////////////////////////////////////////////////////
        private void load_outer_airfoil_MenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                open.Title = "打开翼型文件";
                open.InitialDirectory = System.IO.Directory.GetDirectoryRoot(System.IO.Directory.GetCurrentDirectory());
                open.Filter = "翼型数据文件(*.dat)|*.dat|其他数据文件(*.*)|*.*";
                if (open.ShowDialog() == DialogResult.OK)
                {
                    foil_text.Text = open.FileName;                                   //load filename in foil_text.
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:010", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //////////////////////////////////////////////////////////////////////
        //file tree operate event.////////////////////////////////////////////
        //error code 011./////////////////////////////////////////////////////
        private void file_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (e.Node.Level == 1)                                       //if click the date node.
                {
                    string s = e.Node.FullPath;
                    int ii = s.IndexOf("\\");
                    string firstdirstring = Ppath + "\\outcome" + s.Substring(ii, s.Length - ii) + "\\";
                    DirectoryInfo firstdir = new DirectoryInfo(firstdirstring);
                    FileInfo[] secondfiles = firstdir.GetFiles();
                    bool flag = true;
                    foreach (FileInfo file in secondfiles)                  //traversing all files.
                    {
                        int j = file.FullName.LastIndexOf("\\");
                        string ss = file.FullName.Substring(j + 1, file.FullName.Length - j - 1);
                        if (ss.IndexOf("P_A") >= 0)                        //select parameters file.
                        {
                            if (flag == true)
                            {
                                parapath = file.FullName;                  //if select it, get the route.
                                FileStream nodeb = new FileStream(parapath, FileMode.Open, FileAccess.Read);
                                show_data(nodeb);                          //show parameters.
                                nodeb.Close();
                                flag = false;
                            }
                        }
                        else if (ss.IndexOf("cp_A") >= 0)
                        {
                        }
                        else if (ss.IndexOf(".dat") >= 0)                   //get airfoil data file route.
                        {
                            foilpath = file.FullName;
                        }
                        else if (ss.IndexOf(".cfg") >= 0)
                        {
                        }
                        else if (ss.IndexOf(".mcr") >= 0)
                        {
                        }
                        else if (ss.IndexOf(".xlsx") >= 0)
                        {
                        }
                        else if (ss.IndexOf(".xls") >= 0)
                        {
                        }
                        else
                        {
                            cppath = null;
                            foilpath = null;
                            parapath = null;
                        }
                    }
                }
                if (e.Node.Level == 2)                                       //if click the Cp node.
                {
                    string cpfilenodepath = e.Node.FullPath;
                    int ii2 = cpfilenodepath.LastIndexOf(".");
                    int jj2 = cpfilenodepath.LastIndexOf("\\");
                    int kk2 = cpfilenodepath.IndexOf("\\");
                    if (cpfilenodepath.Substring(jj2 + 1, ii2 - jj2 - 1).IndexOf("cp_A") >= 0)
                    {                                                       //get the Cp file route string.
                        cppath = Ppath + "\\outcome" + cpfilenodepath.Substring(kk2, cpfilenodepath.Length - kk2);
                    }
                    string dir2string = Ppath + "\\outcome" + cpfilenodepath.Substring(kk2, jj2 - kk2 + 1);
                    DirectoryInfo dir2 = new DirectoryInfo(dir2string);
                    FileInfo[] files2 = dir2.GetFiles();
                    bool flag = true;
                    foreach (FileInfo file2 in files2)                      //traversing all files.
                    {
                        int j2 = file2.FullName.LastIndexOf("\\");
                        string filenm = file2.FullName.Substring(j2 + 1, file2.FullName.Length - j2 - 1);
                        if (filenm.IndexOf("P_A") >= 0)
                        {
                            if (flag == true)
                            {
                                parapath = file2.FullName;
                                FileStream nodeb2 = new FileStream(parapath, FileMode.Open, FileAccess.Read);
                                show_data(nodeb2);                              //show parameters.
                                nodeb2.Close();
                                flag = false;
                            }
                        }
                        else if (filenm.IndexOf("cp_A") >= 0)
                        {
                        }
                        else if (filenm.IndexOf(".dat") >= 0)               //get airfoil data file route.
                        {
                            foilpath = file2.FullName;
                        }
                        else if (filenm.IndexOf(".cfg") >= 0)
                        {
                        }
                        else if (filenm.IndexOf(".mcr") >= 0)
                        {
                        }
                        else if (filenm.IndexOf(".xlsx") >= 0)
                        {
                        }
                        else if (filenm.IndexOf(".xls") >= 0)
                        {
                        }
                        else
                        {
                            cppath = null;
                            foilpath = null;
                            parapath = null;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:011", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ////////////////////////////////////////////////////////
        //plot airfoil graph.///////////////////////////////////
        //error code 012.///////////////////////////////////////
        private void foil_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(foilpath))                            //judge the foilpath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的翼型数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                FileStream foilfile = null;                                    //declare airfoil file filestream.
                string foilname = null;                                        //declare airfoil name string.
                if (!string.IsNullOrEmpty(foilpath))
                {
                    int l = foilpath.LastIndexOf(".");
                    int m = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(m + 1, l - m - 1);           //get the airfoil name.
                    foilfile = new FileStream(foilpath, FileMode.Open, FileAccess.Read);
                }

                StreamReader reader = new StreamReader(foilfile);
                List<List<double>> listXY = new List<List<double>>();
                string coor = null;
                GraphPane foilpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                reader.ReadLine();

                while (!string.IsNullOrEmpty(coor = reader.ReadLine()))
                {
                    string[] foilArr = coor.Trim().Split(new char[] { '\t', ' ' });
                    List<double> templist = new List<double>();
                    foreach (string s in foilArr)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            templist.Add(double.Parse(s));
                        }
                    }
                    listXY.Add(templist);
                }
                reader.Close();
                foilfile.Close();

                double[] X = new double[listXY.Count];
                double[] Y = new double[listXY.Count];
                for (int i = 0; i < listXY.Count; i++)
                {
                    X[i] = listXY[i][0];
                    Y[i] = listXY[i][1];
                }

                foilpane.Title.Text = "Airfoil";
                foilpane.XAxis.Title.Text = "Chord Location";
                foilpane.YAxis.Title.Text = "Deep Location";

                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                foilpane.Title.FontSpec = font;
                foilpane.XAxis.Title.FontSpec = font;
                foilpane.YAxis.Title.FontSpec = font;
                foilpane.YAxis.Scale.Max = 0.48;                              //define the graph axis scale.
                foilpane.YAxis.Scale.Min = -0.48;
                foilpane.XAxis.Scale.Max = 1.2;
                foilpane.XAxis.Scale.Min = -0.2;
                foilpane.YAxis.Scale.IsReverse = false;                       //Y axis is not reversed.

                LineItem foilcurve = foilpane.AddCurve(foilname, X, Y, Color.Red, SymbolType.None);
                gra.AxisChange();
                gra.Refresh();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:012", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////
        //plot Cp graph./////////////////////////////////////
        //error code 013.////////////////////////////////////
        private void cp_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(cppath))                             //judge the cppath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的Cp文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                string aoastatus = null;                                      //angle of attack status.
                string mastatus = null;                                       //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                string title = null;                                          //title for differ data. 
                FileStream cpfile = null;
                if ((!string.IsNullOrEmpty(cppath)) && (!string.IsNullOrEmpty(foilpath)))
                {
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                    cpfile = new FileStream(cppath, FileMode.Open, FileAccess.Read);
                    int ialfa = cppath.LastIndexOf("_A");
                    int ima = cppath.LastIndexOf("_Ma");
                    int jma = cppath.LastIndexOf(".");
                    aoastatus = cppath.Substring(ialfa + 2, ima - ialfa - 2); //read in aoa status.
                    mastatus = cppath.Substring(ima + 3, jma - ima - 3);      //read in ma status.
                    title = foilname + "@α " + aoastatus + "@Ma " + mastatus;
                    DirectoryInfo dirr = new DirectoryInfo(cppath.Substring(0, cppath.LastIndexOf("\\") + 1));
                    FileInfo[] ff = dirr.GetFiles();
                    foreach (FileInfo f in ff)
                    {
                        if (f.FullName.IndexOf("deployment.cfg") >= 0)        //read in re status and xtr status.
                        {
                            FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                            StreamReader cfgreader = new StreamReader(cfgfile);
                            string content = cfgreader.ReadLine();
                            if (!string.IsNullOrEmpty(content))               //if there is a string, it must be Reynold's atatus.
                            {
                                restatus = content;
                                title = title + "Re " + restatus;
                            }
                            content = cfgreader.ReadLine();
                            if (!string.IsNullOrEmpty(content))              //if there is another line of string, it must be xtr status.
                            {
                                xtrstatus = content;
                                title = title + "xtr " + xtrstatus;
                            }
                            cfgreader.Close();
                            cfgfile.Close();
                        }
                    }
                }

                StreamReader reader = new StreamReader(cpfile);
                List<List<double>> listcp = new List<List<double>>();
                string temp = null;
                GraphPane cppane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                reader.ReadLine();

                while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
                {
                    string[] cpArr = temp.Trim().Split(' ');
                    List<double> templist = new List<double>();
                    foreach (string s in cpArr)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            templist.Add(double.Parse(s));
                        }
                    }
                    listcp.Add(templist);
                }
                reader.Close();
                cpfile.Close();

                double[] X = new double[listcp.Count];
                double[] Y = new double[listcp.Count];
                for (int i = 0; i < listcp.Count; i++)
                {
                    X[i] = listcp[i][0];
                    Y[i] = listcp[i][1];
                }
                cppane.Title.Text = "Cp Graph";
                cppane.XAxis.Title.Text = "Chord location";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                cppane.Title.FontSpec = font;
                cppane.XAxis.Title.FontSpec = font;
                cppane.XAxis.Scale.MaxAuto = true;
                cppane.XAxis.Scale.MinAuto = true;
                cppane.YAxis.Scale.MaxAuto = true;
                cppane.YAxis.Scale.MinAuto = true;
                cppane.YAxis.Scale.IsReverse = true;                               //define reversed Y axis only for Cp graph.
                cppane.YAxis.Title.Text = "Cp";
                cppane.YAxis.Title.FontSpec = font;

                LineItem cpcurve = cppane.AddCurve(title, X, Y, Color.Red, SymbolType.Plus);
                gra.AxisChange();
                gra.Refresh();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:013", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////
        //plot Cl graph//////////////////////////////////////
        //error code 014.////////////////////////////////////
        private void cl_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(parapath))                           //judge the parapath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<List<double>> listp = new List<List<double>>();
                GraphPane clpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                List<string> mastatus = new List<string>();                   //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                List<string> title = new List<string>();                     //title for differ data. 
                Color[] color = { Color.Black, Color.Blue, Color.Brown, Color.Fuchsia, Color.Gray, Color.Green, Color.Orchid, Color.Purple, Color.Red, Color.Yellow };
                SymbolType[] symbol = { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.VDash, SymbolType.HDash };
                if ((!string.IsNullOrEmpty(parapath)) && (!string.IsNullOrEmpty(foilpath)))
                {                                                             //get the airfoil name.
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                }

                DirectoryInfo dirr = new DirectoryInfo(parapath.Substring(0, parapath.LastIndexOf("\\") + 1));
                FileInfo[] ff = dirr.GetFiles();
                foreach (FileInfo f in ff)
                {
                    if (f.FullName.IndexOf("outdata.cfg") >= 0)                //read in all parameters.
                    {
                        FileStream outdatafile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader reader = new StreamReader(outdatafile);
                        string row = null;
                        while (!string.IsNullOrEmpty(row = reader.ReadLine()))
                        {
                            if (row.IndexOf("10086.0") == -1)
                            {
                                string[] ds = row.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in ds)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                listp.Add(pararow);
                            }
                        }
                        reader.Close();
                        outdatafile.Close();
                    }

                    if (f.FullName.IndexOf("deployment.cfg") >= 0)             //read in re status and xtr status.
                    {
                        FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader cfgreader = new StreamReader(cfgfile);
                        string content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            restatus = "@Re " + content;
                        }
                        content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            xtrstatus = "@xtr " + content;
                        }
                        cfgreader.Close();
                        cfgfile.Close();
                    }
                }

                double tempma = listp[0][0];
                mastatus.Add(Convert.ToString(tempma));
                List<int> maflag = new List<int>();
                for (int ima = 1; ima < listp.Count; ima++)
                {
                    if (!(listp[ima][0] == tempma))                                    //differ differential ma.
                    {
                        maflag.Add(ima);                                             //the next different ma position in listp.
                        tempma = listp[ima][0];
                        mastatus.Add(Convert.ToString(tempma));
                    }
                }
                maflag.Add(listp.Count);
                if (mastatus.Count > 9)                                                //if the count of Mach number greater than ten, the graph couldn't display.
                {
                    MessageBox.Show("请保证一次计算的不同马赫数数量不大于10个，否则图形无法显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                clpane.Title.Text = "Cl Graph";
                clpane.XAxis.Title.Text = "α";
                clpane.YAxis.Title.Text = "Cl";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                clpane.Title.FontSpec = font;
                clpane.XAxis.Title.FontSpec = font;
                clpane.YAxis.Title.FontSpec = font;
                clpane.YAxis.Scale.IsReverse = false;
                clpane.XAxis.Scale.MaxAuto = true;
                clpane.XAxis.Scale.MinAuto = true;
                clpane.YAxis.Scale.MaxAuto = true;
                clpane.YAxis.Scale.MinAuto = true;
                for (int i = 0; i < mastatus.Count; i++)
                {
                    if (i == 0)                                                      //output the first line.
                    {
                        double[] X = new double[maflag[0]];
                        double[] Y = new double[maflag[0]];
                        for (int i0 = 0; i0 < maflag[0]; i0++)
                        {
                            X[i0] = listp[i0][1];
                            Y[i0] = listp[i0][2];
                        }
                        title.Add(foilname + "@Ma " + mastatus[0] + restatus + xtrstatus);
                        LineItem clcurve = clpane.AddCurve(title[0], X, Y, color[0], symbol[0]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                    else                                                          //output other line using different method.
                    {
                        double[] X = new double[maflag[i] - maflag[i - 1]];
                        double[] Y = new double[maflag[i] - maflag[i - 1]];
                        for (int i1 = maflag[i - 1]; i1 < maflag[i]; i1++)
                        {
                            X[i1 - maflag[i - 1]] = listp[i1][1];
                            Y[i1 - maflag[i - 1]] = listp[i1][2];
                        }
                        title.Add(foilname + "@Ma " + mastatus[i] + restatus + xtrstatus);
                        LineItem clcurve = clpane.AddCurve(title[i], X, Y, color[i], symbol[i]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:014", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        /////////////////////////////////////////////////////
        //plot Cd graph//////////////////////////////////////
        //error code 015.////////////////////////////////////
        private void cd_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(parapath))                           //judge the parapath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<List<double>> listp = new List<List<double>>();
                GraphPane cdpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                List<string> mastatus = new List<string>();                   //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                List<string> title = new List<string>();                      //title for differ data. 
                Color[] color = { Color.Black, Color.Blue, Color.Brown, Color.Fuchsia, Color.Gray, Color.Green, Color.Orchid, Color.Purple, Color.Red, Color.Yellow };
                SymbolType[] symbol = { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.VDash, SymbolType.HDash };
                if ((!string.IsNullOrEmpty(parapath)) && (!string.IsNullOrEmpty(foilpath)))
                {                                                             //get the airfoil name.
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                }

                DirectoryInfo dirr = new DirectoryInfo(parapath.Substring(0, parapath.LastIndexOf("\\") + 1));
                FileInfo[] ff = dirr.GetFiles();
                foreach (FileInfo f in ff)
                {
                    if (f.FullName.IndexOf("outdata.cfg") >= 0)                //read in all parameters.
                    {
                        FileStream outdatafile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader reader = new StreamReader(outdatafile);
                        string row = null;
                        while (!string.IsNullOrEmpty(row = reader.ReadLine()))
                        {
                            if (row.IndexOf("10086.0") == -1)
                            {
                                string[] ds = row.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in ds)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                listp.Add(pararow);
                            }
                        }
                        reader.Close();
                        outdatafile.Close();
                    }

                    if (f.FullName.IndexOf("deployment.cfg") >= 0)                     //read in re status and xtr status.
                    {
                        FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader cfgreader = new StreamReader(cfgfile);
                        string content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            restatus = "@Re " + content;
                        }
                        content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            xtrstatus = "@xtr " + content;
                        }
                        cfgreader.Close();
                        cfgfile.Close();
                    }
                }
                if (listp[0][3] == 0)
                {
                    return;
                }

                double tempma = listp[0][0];
                mastatus.Add(Convert.ToString(tempma));
                List<int> maflag = new List<int>();
                for (int ima = 1; ima < listp.Count; ima++)
                {
                    if (!(listp[ima][0] == tempma))                                    //differ differential ma.
                    {
                        maflag.Add(ima);                                               //the next different ma position in listp.
                        tempma = listp[ima][0];
                        mastatus.Add(Convert.ToString(tempma));
                    }
                }
                maflag.Add(listp.Count);
                if (mastatus.Count > 9)                                                //if the count of Mach number greater than ten, the graph couldn't display.
                {
                    MessageBox.Show("请保证一次计算的不同马赫数数量不大于10个，否则图形无法显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                cdpane.Title.Text = "Cd Graph";
                cdpane.XAxis.Title.Text = "α";
                cdpane.YAxis.Title.Text = "Cd";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                cdpane.Title.FontSpec = font;
                cdpane.XAxis.Title.FontSpec = font;
                cdpane.YAxis.Title.FontSpec = font;
                cdpane.YAxis.Scale.IsReverse = false;
                cdpane.XAxis.Scale.MaxAuto = true;
                cdpane.XAxis.Scale.MinAuto = true;
                cdpane.YAxis.Scale.MaxAuto = true;
                cdpane.YAxis.Scale.MinAuto = true;
                for (int i = 0; i < mastatus.Count; i++)
                {
                    if (i == 0)                                                      //output the first line.
                    {
                        double[] X = new double[maflag[0]];
                        double[] Y = new double[maflag[0]];
                        for (int i0 = 0; i0 < maflag[0]; i0++)
                        {
                            X[i0] = listp[i0][1];
                            Y[i0] = listp[i0][3];
                        }
                        title.Add(foilname + "@Ma " + mastatus[0] + restatus + xtrstatus);
                        LineItem cdcurve = cdpane.AddCurve(title[0], X, Y, color[0], symbol[0]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                    else                                                           //output other line using different method.
                    {
                        double[] X = new double[maflag[i] - maflag[i - 1]];
                        double[] Y = new double[maflag[i] - maflag[i - 1]];
                        for (int i1 = maflag[i - 1]; i1 < maflag[i]; i1++)
                        {
                            X[i1 - maflag[i - 1]] = listp[i1][1];
                            Y[i1 - maflag[i - 1]] = listp[i1][3];
                        }
                        title.Add(foilname + "@Ma " + mastatus[i] + restatus + xtrstatus);
                        LineItem cdcurve = cdpane.AddCurve(title[i], X, Y, color[i], symbol[i]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:015", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////////
        //plot drag polar graph///////////////////////////////////////
        //error code 016.//////////////////////////////////////
        private void polar_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(parapath))                           //judge the parapath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<List<double>> listp = new List<List<double>>();
                GraphPane polarpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                List<string> mastatus = new List<string>();                   //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                List<string> title = new List<string>();                      //title for differ data. 
                Color[] color = { Color.Black, Color.Blue, Color.Brown, Color.Fuchsia, Color.Gray, Color.Green, Color.Orchid, Color.Purple, Color.Red, Color.Yellow };
                SymbolType[] symbol = { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.VDash, SymbolType.HDash };
                if ((!string.IsNullOrEmpty(parapath)) && (!string.IsNullOrEmpty(foilpath)))
                {                                                             //get the airfoil name.
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                }

                DirectoryInfo dirr = new DirectoryInfo(parapath.Substring(0, parapath.LastIndexOf("\\") + 1));
                FileInfo[] ff = dirr.GetFiles();
                foreach (FileInfo f in ff)
                {
                    if (f.FullName.IndexOf("outdata.cfg") >= 0)                        //read in all parameters.
                    {
                        FileStream outdatafile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader reader = new StreamReader(outdatafile);
                        string row = null;
                        while (!string.IsNullOrEmpty(row = reader.ReadLine()))
                        {
                            if (row.IndexOf("10086.0") == -1)
                            {
                                string[] ds = row.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in ds)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                listp.Add(pararow);
                            }
                        }
                        reader.Close();
                        outdatafile.Close();
                    }

                    if (f.FullName.IndexOf("deployment.cfg") >= 0)                     //read in re status and xtr status.
                    {
                        FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader cfgreader = new StreamReader(cfgfile);
                        string content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            restatus = "@Re " + content;
                        }
                        content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            xtrstatus = "@xtr " + content;
                        }
                        cfgreader.Close();
                        cfgfile.Close();
                    }
                }
                if (listp[0][3] == 0)
                {
                    return;
                }

                double tempma = listp[0][0];
                mastatus.Add(Convert.ToString(tempma));
                List<int> maflag = new List<int>();
                for (int ima = 1; ima < listp.Count; ima++)
                {
                    if (!(listp[ima][0] == tempma))                                    //differ differential ma.
                    {
                        maflag.Add(ima);                                               //the next different ma position in listp.
                        tempma = listp[ima][0];
                        mastatus.Add(Convert.ToString(tempma));
                    }
                }
                maflag.Add(listp.Count);
                if (mastatus.Count > 9)                                                //if the count of Mach number greater than ten, the graph couldn't display.
                {
                    MessageBox.Show("请保证一次计算的不同马赫数数量不大于10个，否则图形无法显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                polarpane.Title.Text = "Polar Graph";
                polarpane.XAxis.Title.Text = "Cd";
                polarpane.YAxis.Title.Text = "Cl";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                polarpane.Title.FontSpec = font;
                polarpane.XAxis.Title.FontSpec = font;
                polarpane.YAxis.Title.FontSpec = font;
                polarpane.YAxis.Scale.IsReverse = false;
                polarpane.XAxis.Scale.MaxAuto = true;
                polarpane.XAxis.Scale.MinAuto = true;
                polarpane.YAxis.Scale.MaxAuto = true;
                polarpane.YAxis.Scale.MinAuto = true;
                for (int i = 0; i < mastatus.Count; i++)
                {
                    if (i == 0)                                                      //output the first line.
                    {
                        double[] X = new double[maflag[0]];
                        double[] Y = new double[maflag[0]];
                        for (int i0 = 0; i0 < maflag[0]; i0++)
                        {
                            X[i0] = listp[i0][3];
                            Y[i0] = listp[i0][2];
                        }
                        title.Add(foilname + "@Ma " + mastatus[0] + restatus + xtrstatus);
                        LineItem polarcurve = polarpane.AddCurve(title[0], X, Y, color[0], symbol[0]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                    else                                                           //output other line using different method.
                    {
                        double[] X = new double[maflag[i] - maflag[i - 1]];
                        double[] Y = new double[maflag[i] - maflag[i - 1]];
                        for (int i1 = maflag[i - 1]; i1 < maflag[i]; i1++)
                        {
                            X[i1 - maflag[i - 1]] = listp[i1][3];
                            Y[i1 - maflag[i - 1]] = listp[i1][2];
                        }
                        title.Add(foilname + "@Ma " + mastatus[i] + restatus + xtrstatus);
                        LineItem polarcurve = polarpane.AddCurve(title[i], X, Y, color[i], symbol[i]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:016", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////
        //plot Cm graph//////////////////////////////////////
        //error code 017.////////////////////////////////////
        private void cm_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(parapath))                           //judge the parapath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<List<double>> listp = new List<List<double>>();
                GraphPane cmpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                List<string> mastatus = new List<string>();                   //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                List<string> title = new List<string>();                      //title for differ data. 
                Color[] color = { Color.Black, Color.Blue, Color.Brown, Color.Fuchsia, Color.Gray, Color.Green, Color.Orchid, Color.Purple, Color.Red, Color.Yellow };
                SymbolType[] symbol = { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.VDash, SymbolType.HDash };
                if ((!string.IsNullOrEmpty(parapath)) && (!string.IsNullOrEmpty(foilpath)))
                {                                                             //get the airfoil name.
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                }

                DirectoryInfo dirr = new DirectoryInfo(parapath.Substring(0, parapath.LastIndexOf("\\") + 1));
                FileInfo[] ff = dirr.GetFiles();
                foreach (FileInfo f in ff)
                {
                    if (f.FullName.IndexOf("outdata.cfg") >= 0)                        //read in all parameters.
                    {
                        FileStream outdatafile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader reader = new StreamReader(outdatafile);
                        string row = null;
                        while (!string.IsNullOrEmpty(row = reader.ReadLine()))
                        {
                            if (row.IndexOf("10086.0") == -1)
                            {
                                string[] ds = row.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in ds)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                listp.Add(pararow);
                            }
                        }
                        reader.Close();
                        outdatafile.Close();
                    }

                    if (f.FullName.IndexOf("deployment.cfg") >= 0)                     //read in re status and xtr status.
                    {
                        FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader cfgreader = new StreamReader(cfgfile);
                        string content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            restatus = "@Re " + content;
                        }
                        content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            xtrstatus = "@xtr " + content;
                        }
                        cfgreader.Close();
                        cfgfile.Close();
                    }
                }

                double tempma = listp[0][0];
                mastatus.Add(Convert.ToString(tempma));
                List<int> maflag = new List<int>();
                for (int ima = 1; ima < listp.Count; ima++)
                {
                    if (!(listp[ima][0] == tempma))                                    //differ differential ma.
                    {
                        maflag.Add(ima);                                               //the next different ma position in listp.
                        tempma = listp[ima][0];
                        mastatus.Add(Convert.ToString(tempma));
                    }
                }
                maflag.Add(listp.Count);
                if (mastatus.Count > 9)                                                //if the count of Mach number greater than ten, the graph couldn't display.
                {
                    MessageBox.Show("请保证一次计算的不同马赫数数量不大于10个，否则图形无法显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                cmpane.Title.Text = "Cm Graph";
                cmpane.XAxis.Title.Text = "α";
                cmpane.YAxis.Title.Text = "Cm";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                cmpane.Title.FontSpec = font;
                cmpane.XAxis.Title.FontSpec = font;
                cmpane.YAxis.Title.FontSpec = font;
                cmpane.YAxis.Scale.IsReverse = false;
                cmpane.XAxis.Scale.MaxAuto = true;
                cmpane.XAxis.Scale.MinAuto = true;
                cmpane.YAxis.Scale.MaxAuto = true;
                cmpane.YAxis.Scale.MinAuto = true;
                for (int i = 0; i < mastatus.Count; i++)
                {
                    if (i == 0)                                                      //output the first line.
                    {
                        double[] X = new double[maflag[0]];
                        double[] Y = new double[maflag[0]];
                        for (int i0 = 0; i0 < maflag[0]; i0++)
                        {
                            X[i0] = listp[i0][1];
                            Y[i0] = listp[i0][5];
                        }
                        title.Add(foilname + "@Ma " + mastatus[0] + restatus + xtrstatus);
                        LineItem cmcurve = cmpane.AddCurve(title[0], X, Y, color[0], symbol[0]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                    else                                                           //output other line using different method.
                    {
                        double[] X = new double[maflag[i] - maflag[i - 1]];
                        double[] Y = new double[maflag[i] - maflag[i - 1]];
                        for (int i1 = maflag[i - 1]; i1 < maflag[i]; i1++)
                        {
                            X[i1 - maflag[i - 1]] = listp[i1][1];
                            Y[i1 - maflag[i - 1]] = listp[i1][5];
                        }
                        title.Add(foilname + "@Ma " + mastatus[i] + restatus + xtrstatus);
                        LineItem cmcurve = cmpane.AddCurve(title[i], X, Y, color[i], symbol[i]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:017", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////////
        //plot Cl/Cd graph/////////////////////////////////////
        //error code 018.//////////////////////////////////////
        private void ld_gra_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(parapath))                           //judge the parapath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的数据文件夹或者其中的任意文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                List<List<double>> listp = new List<List<double>>();
                GraphPane ldpane = gra.GraphPane;
                gra.GraphPane.CurveList.Clear();

                string foilname = null;
                string restatus = null;                                       //Reynold's number status.
                List<string> mastatus = new List<string>();                   //Mach number status.
                string xtrstatus = null;                                      //xtr status.
                List<string> title = new List<string>();                      //title for differ data. 
                Color[] color = { Color.Black, Color.Blue, Color.Brown, Color.Fuchsia, Color.Gray, Color.Green, Color.Orchid, Color.Purple, Color.Red, Color.Yellow };
                SymbolType[] symbol = { SymbolType.Circle, SymbolType.Diamond, SymbolType.Plus, SymbolType.Square, SymbolType.Star, SymbolType.Triangle, SymbolType.TriangleDown, SymbolType.XCross, SymbolType.VDash, SymbolType.HDash };
                if ((!string.IsNullOrEmpty(parapath)) && (!string.IsNullOrEmpty(foilpath)))
                {                                                             //get the airfoil name.
                    int ifoil = foilpath.LastIndexOf(".");
                    int jfoil = foilpath.LastIndexOf("\\");
                    foilname = foilpath.Substring(jfoil + 1, ifoil - jfoil - 1);
                }

                DirectoryInfo dirr = new DirectoryInfo(parapath.Substring(0, parapath.LastIndexOf("\\") + 1));
                FileInfo[] ff = dirr.GetFiles();
                foreach (FileInfo f in ff)
                {
                    if (f.FullName.IndexOf("outdata.cfg") >= 0)                        //read in all parameters.
                    {
                        FileStream outdatafile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader reader = new StreamReader(outdatafile);
                        string row = null;
                        while (!string.IsNullOrEmpty(row = reader.ReadLine()))
                        {
                            if (row.IndexOf("10086.0") == -1)
                            {
                                string[] ds = row.Trim().Split(' ');
                                List<double> pararow = new List<double>();
                                foreach (string s in ds)
                                {
                                    if (!string.IsNullOrEmpty(s))
                                    {
                                        pararow.Add(double.Parse(s));
                                    }
                                }
                                listp.Add(pararow);
                            }
                        }
                        reader.Close();
                        outdatafile.Close();
                    }

                    if (f.FullName.IndexOf("deployment.cfg") >= 0)                     //read in re status and xtr status.
                    {
                        FileStream cfgfile = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
                        StreamReader cfgreader = new StreamReader(cfgfile);
                        string content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            restatus = "@Re " + content;
                        }
                        content = cfgreader.ReadLine();
                        if (!string.IsNullOrEmpty(content))
                        {
                            xtrstatus = "@xtr " + content;
                        }
                        cfgreader.Close();
                        cfgfile.Close();
                    }
                }
                if (listp[0][3] == 0)
                {
                    return;
                }

                double tempma = listp[0][0];
                mastatus.Add(Convert.ToString(tempma));
                List<int> maflag = new List<int>();
                for (int ima = 1; ima < listp.Count; ima++)
                {
                    if (!(listp[ima][0] == tempma))                                    //differ differential ma.
                    {
                        maflag.Add(ima);                                               //the next different ma position in listp.
                        tempma = listp[ima][0];
                        mastatus.Add(Convert.ToString(tempma));
                    }
                }
                maflag.Add(listp.Count);
                if (mastatus.Count > 9)                                                //if the count of Mach number greater than ten, the graph couldn't display.
                {
                    MessageBox.Show("请保证一次计算的不同马赫数数量不大于10个，否则图形无法显示", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                ldpane.Title.Text = "L/D Graph";
                ldpane.XAxis.Title.Text = "α";
                ldpane.YAxis.Title.Text = "L/D";
                FontSpec font = new FontSpec("Times New Roman", 20, Color.Black, false, false, false);
                FontSpec font1 = new FontSpec("Times New Roman", 24, Color.Black, false, false, false);
                ldpane.Title.FontSpec = font1;
                ldpane.XAxis.Title.FontSpec = font;
                ldpane.YAxis.Title.FontSpec = font;
                ldpane.YAxis.Scale.IsReverse = false;
                ldpane.XAxis.Scale.MaxAuto = true;
                ldpane.XAxis.Scale.MinAuto = true;
                ldpane.YAxis.Scale.MaxAuto = true;
                ldpane.YAxis.Scale.MinAuto = true;
                for (int i = 0; i < mastatus.Count; i++)
                {
                    if (i == 0)                                                      //output the first line.
                    {
                        double[] X = new double[maflag[0]];
                        double[] Y = new double[maflag[0]];
                        for (int i0 = 0; i0 < maflag[0]; i0++)
                        {
                            X[i0] = listp[i0][1];
                            Y[i0] = listp[i0][2] / listp[i0][3];
                        }
                        title.Add(foilname + "@Ma " + mastatus[0] + restatus + xtrstatus);
                        LineItem ldcurve = ldpane.AddCurve(title[0], X, Y, color[0], symbol[0]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                    else                                                           //output other line using different method.
                    {
                        double[] X = new double[maflag[i] - maflag[i - 1]];
                        double[] Y = new double[maflag[i] - maflag[i - 1]];
                        for (int i1 = maflag[i - 1]; i1 < maflag[i]; i1++)
                        {
                            X[i1 - maflag[i - 1]] = listp[i1][1];
                            Y[i1 - maflag[i - 1]] = listp[i1][2] / listp[i1][3];
                        }
                        title.Add(foilname + "@Ma " + mastatus[i] + restatus + xtrstatus);
                        LineItem ldcurve = ldpane.AddCurve(title[i], X, Y, color[i], symbol[i]);
                        gra.AxisChange();
                        gra.Refresh();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档。\r\nEC:018", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////////////////////////////////
        //single select button limit.//////////////////////////////////////////////////
        private void nonviscous_singlebutton_MouseClick(object sender, MouseEventArgs e)
        {
            xtr_text.Enabled = false;                              //if select non_viscous, xtr_text, viscous_singlebutton, re_text were disabled.
            viscous_singlebutton.Checked = false;
            re_text.Enabled = false;
        }

        ////////////////////////////////////////////////////////////////////////////
        //single select button limit.///////////////////////////////////////////////
        private void viscous_singlebutton_MouseClick(object sender, MouseEventArgs e)
        {
            xtr_text.Enabled = true;
            nonviscous_singlebutton.Checked = false;              //if select viscous, nonviscous_singlebutton was disabled.
            re_text.Enabled = true;
        }

        //////////////////////////////////////////////////////////////
        //aoa1_text and yjjg_text limit.//////////////////////////////
        //error code 019./////////////////////////////////////////////
        private void aoa0_text_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string temp_text=aoa0_text.Text;
                if (temp_text.IndexOf(' ')>0)               //if man type in space value.
                {
                    aoa1_text.Enabled = false;
                    yjjg_text.Enabled = false;
                }
                else
                {
                    aoa1_text.Enabled = true;
                    yjjg_text.Enabled = true;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:019", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //////////////////////////////////////////////////////////////////////
        //open working directory./////////////////////////////////////////////
        //error code 020./////////////////////////////////////////////////////
        private void working_folder_MenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(Ppath + "\\outcome");
                string sdir = Convert.ToString(dir);
                if (dir.Exists)
                {
                    System.Diagnostics.Process.Start("explorer.exe", sdir);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:020", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        ///////////////////////////////////////////////////////////////////
        //save parameters into excel file./////////////////////////////////
        //error code 021.//////////////////////////////////////////////////
        private void paratoexcel_MenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //open save as dialog.
                SaveFileDialog saveexcel = new SaveFileDialog();
                saveexcel.Filter = "MS Office 2007/2010/2013 Excel文件(*.xlsx)|*.xlsx|MS Office 2003文件(*.xls)|*.xls|所有文件(*.*)|*.*";
                saveexcel.Title = "数据另存为";
                saveexcel.FileName = "parameters.xlsx";                             //set default file name.
                string excelname = null;
                if (saveexcel.ShowDialog() == DialogResult.OK)
                {
                    excelname = saveexcel.FileName;                                 //get excel file name.
                }

                FileStream para = new FileStream(parapath, FileMode.Open, FileAccess.Read);
                Microsoft.Office.Interop.Excel.Application paraexcel = new Microsoft.Office.Interop.Excel.Application();
                _Workbook pworkbook = paraexcel.Workbooks.Add(true);                //add workbook in excel file.
                _Worksheet pworksheet = (_Worksheet)pworkbook.ActiveSheet;          //active worksheet.
                List<List<string>> paralist = new List<List<string>>();
                List<string> itemlist = new List<string>();
                StreamReader reader = new StreamReader(para);                       //open and read parameter data.
                string title = null;
                string temp = null;
                paraexcel.Visible = false;                                          //do not open when save successfully.
                pworksheet.get_Range(paraexcel.Cells[1, 1], paraexcel.Cells[1, 8]).MergeCells = true;
                //merge the units from A1:H1.

                //read in and write in the title.
                reader.ReadLine();
                title = title + reader.ReadLine() + "\r\n";
                reader.ReadLine();
                title = title + reader.ReadLine();
                reader.ReadLine();
                title = title + reader.ReadLine() + "\r\n";
                reader.ReadLine();
                title = title + reader.ReadLine() + "\r\n";
                title = title + reader.ReadLine() + "\r\n";
                paraexcel.Cells[1, 1] = title;                                      //write in title and set title column height.
                ((Microsoft.Office.Interop.Excel.Range)pworksheet.Rows["1:1", System.Type.Missing]).RowHeight = 76;
                reader.ReadLine();

                //read in and write in caption items.
                string[] item = reader.ReadLine().Trim().Split(' ');
                itemlist.Add("Ma");
                foreach (string item0 in item)
                {
                    if (!string.IsNullOrEmpty(item0))
                    {
                        itemlist.Add(item0);
                    }
                }
                for (int a = 0; a < itemlist.Count; a++)
                {
                    paraexcel.Cells[2, a + 1] = itemlist[a];                             //write in items.
                }
                reader.Close();
                para.Close();

                //read in and write in data.

                FileStream parafile = new FileStream(parapath.Substring(0, parapath.LastIndexOf("\\")) + "\\outdata.cfg", FileMode.Open, FileAccess.Read);
                StreamReader parareader = new StreamReader(parafile);               //open and read in data.
                while (!string.IsNullOrEmpty(temp = parareader.ReadLine()))
                {
                    string[] row = temp.Trim().Split(' ');
                    List<string> rowlist = new List<string>();
                    foreach (string number in row)
                    {
                        if (!string.IsNullOrEmpty(number))
                        {
                            rowlist.Add(number);
                        }
                    }
                    paralist.Add(rowlist);
                }
                parareader.Close();
                parafile.Close();

                for (int i = 0; i < paralist.Count; i++)
                {
                    for (int j = 0; j < paralist[i].Count; j++)
                    {
                        paraexcel.Cells[i + 3, j + 1] = paralist[i][j];             //write in data from paralist to excel file.
                    }
                }

                if (File.Exists(excelname))
                {
                    MessageBox.Show("文件已存在，请确认是否已经保存。如果着实没有保存，请删除\r\n数据保存目录下的parameters.xlsx文件，或者重命名为其它名字！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    pworkbook.SaveAs(excelname, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
                }

                //kill the excel process.
                Process[] pA = Process.GetProcesses();
                foreach (Process p in pA)
                {
                    if (p.ProcessName.ToUpper().Equals("EXCEL"))
                    {
                        p.Kill();
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请确认点选正确的parameters.dat文件，并且保存目录存在，\r\n否则，请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:021", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////////////////////////
        //delete xfoil.exe in user defined working directory.////////////////////
        //error code 022.////////////////////////////////////////////////////////
        private void main_form_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (delxfoil == true)
                {
                    string xfoilpath = Ppath + "\\xfoil.exe";
                    File.Delete(xfoilpath);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:021", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /////////////////////////////////////////////////////////////////
        //plot cp data in tecplot.///////////////////////////////////////
        //error code 022.////////////////////////////////////////////////
        private void cptecplot_MenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(foilpath))                                                //judge the foilpath string is null or empty.
                {
                    MessageBox.Show("请选择要显示的Cp文件夹或者其中的文件，或者开始新的计算。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string folderstring = foilpath.Substring(0, foilpath.LastIndexOf("\\") + 1);       //get the sub-folder path string.

                //create tecplot.mcr file.
                FileStream mcrfile = new FileStream(folderstring + "tecplot.mcr", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriter writer = new StreamWriter(mcrfile);                                   //create or open tecplot.mcr and write in.                                

                //traversing all cp files and get their path string.
                List<string> path = new List<string>();
                List<string> leg = new List<string>();
                DirectoryInfo folder = new DirectoryInfo(folderstring);
                FileInfo[] allfiles = folder.GetFiles();
                foreach (FileInfo file in allfiles)                                                //traversing all files in the dir.
                {
                    string sss = file.Name;
                    if (sss.IndexOf("cp_A") >= 0)                                            //if it is a Cp file, get the path string.
                    {
                        path.Add(file.FullName);
                        int si = sss.IndexOf("cp_A");
                        int sj = sss.IndexOf("_Ma");
                        int sk = sss.LastIndexOf(".");
                        leg.Add("Ma " + sss.Substring(sj + 3, sk - sj - 3) + "AOA " + sss.Substring(si + 4, sj - si - 4));
                    }
                }

                //write the tecplot.mcr file.
                //first frame is different form sequent frames. so write respectively.
                writer.WriteLine("#!MC 1120");
                writer.WriteLine("# Created by Black Ghost in Visual C#.");
                writer.WriteLine("$!VarSet |MFBD| = 'C:\\Documents and Settings\\Administrator\\My Documents'");
                writer.WriteLine("$!READDATASET  '\"" + path[0] + "\" '");
                writer.WriteLine("  READDATAOPTION = NEW");
                writer.WriteLine("  RESETSTYLE = YES");
                writer.WriteLine("  INCLUDETEXT = NO");
                writer.WriteLine("  INCLUDEGEOM = NO");
                writer.WriteLine("  INCLUDECUSTOMLABELS = NO");
                writer.WriteLine("  VARLOADMODE = BYNAME");
                writer.WriteLine("  ASSIGNSTRANDIDS = YES");
                writer.WriteLine("  INITIALPLOTTYPE = XYLINE");
                writer.WriteLine("  VARNAMELIST = '\"V1\" \"V2\"'");
                writer.WriteLine("$!XYLINEAXIS YDETAIL 1 {TITLE{TITLEMODE = USETEXT}}");
                writer.WriteLine("$!XYLINEAXIS YDETAIL 1 {TITLE{TEXT = 'Cp'}}");
                writer.WriteLine("$!XYLINEAXIS XDETAIL 1 {TITLE{TITLEMODE = USETEXT}}");
                writer.WriteLine("$!XYLINEAXIS XDETAIL 1 {TITLE{TEXT = 'x'}}");
                writer.WriteLine("$!GLOBALLINEPLOT LEGEND{SHOW = YES}");
                writer.WriteLine("$!GLOBALLINEPLOT LEGEND{SHOWTEXT = YES}");
                writer.WriteLine("$!LINEMAP [1]  NAME = '" + leg[0] + "'");
                writer.WriteLine();
                for (int i = 1; i < path.Count; i++)
                {
                    writer.WriteLine("$!CREATENEWFRAME");
                    writer.WriteLine("$!READDATASET  '\"" + path[i] + "\" '");
                    writer.WriteLine("  READDATAOPTION = NEW");
                    writer.WriteLine("  RESETSTYLE = YES");
                    writer.WriteLine("  INCLUDETEXT = NO");
                    writer.WriteLine("  INCLUDEGEOM = NO");
                    writer.WriteLine("  INCLUDECUSTOMLABELS = NO");
                    writer.WriteLine("  VARLOADMODE = BYNAME");
                    writer.WriteLine("  ASSIGNSTRANDIDS = YES");
                    writer.WriteLine("  INITIALPLOTTYPE = XYLINE");
                    writer.WriteLine("  VARNAMELIST = '\"V1\" \"V2\"'");
                    writer.WriteLine("$!XYLINEAXIS YDETAIL 1 {TITLE{TITLEMODE = USETEXT}}");
                    writer.WriteLine("$!XYLINEAXIS YDETAIL 1 {TITLE{TEXT = 'Cp'}}");
                    writer.WriteLine("$!XYLINEAXIS XDETAIL 1 {TITLE{TITLEMODE = USETEXT}}");
                    writer.WriteLine("$!XYLINEAXIS XDETAIL 1 {TITLE{TEXT = 'x'}}");
                    writer.WriteLine("$!GLOBALLINEPLOT LEGEND{SHOW = YES}");
                    writer.WriteLine("$!GLOBALLINEPLOT LEGEND{SHOWTEXT = YES}");
                    writer.WriteLine("$!LINEMAP [1]  NAME = '" + leg[i] + "'");
                    writer.WriteLine();
                }
                writer.WriteLine();
                writer.WriteLine("$!PICK SETMOUSEMODE");
                writer.WriteLine("  MOUSEMODE = SELECT");
                writer.WriteLine("$!EXTENDEDCOMMAND ");
                writer.WriteLine("  COMMANDPROCESSORID = 'Multi Frame Manager'");
                writer.WriteLine("  COMMAND = 'TILEFRAMESSQUARE'");
                writer.WriteLine("$!RemoveVar |MFBD|");
                writer.Close();
                mcrfile.Close();

                //open tecplot.mcr using Tecplot.
                Process p = new Process();
                p.StartInfo.FileName = folderstring + "tecplot.mcr";
                p.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请确认点选正确的parameters.dat文件，并且保存目录存在，\r\n否则，请查看帮助文档或者将错误信息告知:\r\nE-Mail:chengfengcool@sina.com.\r\nEC:022", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
     } 
}
